#include<bits/stdc++.h>
#define ll long long
#define L x<<1
#define R x<<1|1
#define mid (l+r>>1)
#define lc L,l,mid
#define rc R,mid+1,r
#define OK Ll<=l&&r<=Rr
#define Root 1,1,ln
#define rep(x,y,z) for(int x=(y);x<=(z);x++)
#define per(x,y,z) for(int x=(y);x>=(z);x--)
#define repn(x) rep(x,1,n)
#define repm(x) rep(x,1,m)
#define pb push_back
#define e(x) for(int i=h[x],y=to[i];i;i=nxt[i],y=to[i])
#define E(x) for(auto y:p[x])
#define Pi pair<int,int>
#define ui unsigned ll
inline int read(){int s=0,w=1;char c=getchar();while(c<48||c>57) {if(c=='-') w=-1;c=getchar();}while(c>=48&&c<=57)s=(s<<1)+(s<<3)+c-48,c=getchar();return s*w;}
inline void pf(int x){if(x<0) putchar('-'),x=-x;if(x>9)pf(x/10);putchar(x%10+48);}
using namespace std;
const int N=1e6+10,M=1e6+5,inf=(1LL<<31)-1,mod=998244353;
const ll llf=1e18;
inline void add(int &a,int b){((a+=b)>=mod) and (a-=mod);}
inline int Add(int a,int b){return add(a,b),a;}
inline int mul(int a,int b){return 1LL*a*b%mod;}
inline void Mul(int &a,int b){a=mul(a,b);}
inline void red(int &a,int b){add(a,mod-b);}
inline int Red(int a,int b){return red(a,b),a;}
inline int qp(int a,int b){if(!b)return 1;int c=qp(a,b>>1);Mul(c,c);if(b&1)Mul(c,a);return c;}
inline int INV(int x){return qp(x,mod-2);}
int n,m,a[N];
struct Tree{
    int rt,f[M],dep[M],h[N],to[N<<1],nxt[N<<1],cnt;
    inline void add_(int a,int b){
        to[++cnt]=b,nxt[cnt]=h[a],h[a]=cnt;
    }
    int siz[N],son[N],top[N],dfn[N],Time;
    inline void dfs(int x,int fa){
        f[x]=fa,dep[x]=dep[fa]+1,siz[x]=1;
        e(x)dfs(y,x),siz[x]+=siz[y],son[x]=siz[y]>siz[son[x]]?y:son[x];
    }
    inline void Dfs(int x,int low){
        top[x]=low,dfn[x]=++Time;
        if(son[x])Dfs(son[x],low);
        e(x)if(y^son[x])Dfs(y,y);
    }
    inline int lca(int x,int y){
        while(top[x]^top[y])dep[top[x]]>dep[top[y]]?x=f[top[x]]:y=f[top[y]];
        return dep[x]<dep[y]?x:y;
    }
    inline int jump(int x,int y){
        while(top[x]^top[y]){
            if(f[top[y]]==x)return top[y];
            y=f[top[y]];
        }
        return son[x];
    }
    inline int calc(int x,int y){
        if(dfn[x]>dfn[y])swap(x,y);
        if(dfn[y]<=dfn[x]+siz[x]-1)return mul(n-siz[jump(x,y)],siz[y]);
        return mul(siz[x],siz[y]);
    }
}t[2];
inline void subtask1(){
    repn(i){
        t[0].f[i]=read();
        if(!t[0].f[i])t[0].rt=i;
        else t[0].add_(t[0].f[i],i);
    }
    repm(i){
        t[1].f[i]=read();
        if(!t[1].f[i])t[1].rt=i;
        else t[1].add_(t[1].f[i],i);
    }
    rep(i,0,1)t[i].dfs(t[i].rt,0),t[i].Dfs(t[i].rt,t[i].rt);
    int ans=0;
    repn(i)a[i]=read();
    repn(x)rep(y,x+1,n)add(ans,mul(t[0].calc(x,y),t[1].dep[t[1].lca(a[x],a[y])]));
    cout <<ans;
}
inline void Main(){
    n=read(),m=read();
    if(n<=1000&&m<=1000)return subtask1(),void();
    cout <<527664804;
}
signed main(){
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout);
	int T=1;
	while(T--)Main();
	return 0;
}